package com.minedata.authorization.config;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@EnableConfigurationProperties(DataSourceProperties.class)
@MapperScan(basePackages = "com.minedata.authorization.mapper")
public class MybatisDataSource {
	@Autowired
	private DataSourceProperties dataSourceProperties;
	// mybaits mapper xml搜索路径
	private final static String mapperLocations = "classpath:mapper/*.xml";

	private static Logger log = LoggerFactory.getLogger(MybatisDataSource.class);

	@Bean(destroyMethod = "close")
	public DataSource dataSource() {
		log.debug("Configruing Write DataSource");

		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl("jdbc:postgresql://" + dataSourceProperties.getHost() + ":" + dataSourceProperties.getPort()
				+ "/" + dataSourceProperties.getDatabase());
		datasource.setDriverClassName(dataSourceProperties.getDriverClassName());
		datasource.setUsername(dataSourceProperties.getUsername());
		datasource.setPassword(dataSourceProperties.getPassword());
		datasource.setInitialSize(dataSourceProperties.getInitialSize());
		datasource.setMaxActive(dataSourceProperties.getMaxActive());
		datasource.setMinIdle(dataSourceProperties.getMinIdle());
		datasource.setMaxWait(dataSourceProperties.getMaxWait());
		datasource.setTestOnBorrow(dataSourceProperties.isTestOnBorrow());
		datasource.setTestWhileIdle(dataSourceProperties.isTestWhileIdle());
		datasource.setValidationQuery(dataSourceProperties.getValidationQuery());
		return datasource;
	}

	@Bean
	public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource());
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));
		return sqlSessionFactoryBean.getObject();
	}

	@Bean
	public PlatformTransactionManager transactionManager() {
		return new DataSourceTransactionManager(dataSource());
	}
}
